<template>
  <div class="treeContainer">
    <!-- 页面切换器 -->
    <div class="panel-title">
      <div class="tab">
        <div
          v-for="(data, index) in tabs"
          :key="index"
          :class="data.selected ? `selected` : `unselected`"
          @click="tabChange"
        >
          <img
            :src="require('@/assets/images/icon/标签页/' + data.img + '.png')"
          />
          <span>{{ data.text }}</span>
        </div>
      </div>
      <div class="bgBar"></div>
    </div>
    <!-- 图层管理 -->
    <transition name="fade1">
      <div class="collaspe" v-show="collapseShow">
        <el-collapse v-model="collapseRef">
          <el-collapse-item
            name="1"
            v-for="(data, index) in legendList"
            :key="index"
          >
            <template #title>
              | {{ data.label }}
              <info-filled />
            </template>
            <div class="smallLegend">
              <div>
                <span
                  >图例：
                  <span style="display: none">{{ data.label }}</span>
                </span>
                <img :src="data.picSrc" class="small" />
              </div>
            </div>
            <span style="margin-right: 10px">透明度:</span>
            <div class="opactiySlider">
              <el-slider v-model="data.opacity" @change="sliderChange(data)" />
            </div>
          </el-collapse-item>
          <div class="emptyLegend" v-show="emptyShow">
            <img src="@/assets/images/icon/标签页/空盒子.png" />
            <p>暂无图层</p>
          </div>
        </el-collapse>
      </div>
    </transition>
    <!-- 图层开关 -->
    <transition name="fade1">
      <div v-show="treeShow">
        <!-- 图层搜索框 -->
        <div class="layerSearcher">
          <el-input
            v-model="layerName"
            class="input-with-select"
            placeholder="请输入"
            @keypress="handleKeyPress"
          >
            <template #append>
              <el-button @click="layerSearch">
                <img
                  src="@/assets/images/icon/toolBar/框选查询.png"
                  alt="搜索"
                  style="width: 15px"
                />
              </el-button>
            </template>
          </el-input>
        </div>
        <div>
          <!-- 基础图层 -->
          <div class="tree">
            <el-tree
              :data="tree"
              ref="commonTreeRef"
              show-checkbox
              node-key="id"
              :default-expanded-keys="[-1]"
              @check-change="handleNodeCheckMain"
            />
          </div>
          <!-- 自定义标注图层 -->
          <div class="tree">
            <el-tree
              :key="timeStamp"
              :data="diyTree"
              ref="diyTreeRef"
              show-checkbox
              auto-expand-parent
              node-key="id"
              :default-expanded-keys="[-1]"
              @check-change="handleNodeCheckDIY"
            >
              <template #default="{ node, data }">
                <span class="nodeLabel"> {{ node.label }}</span>
                <img
                  src="@/assets/images/icon/标签页/详细信息.png"
                  @click="getDetail(data)"
                  class="nodeIcon"
                  v-show="data.iconShow"
                />
              </template>
            </el-tree>
          </div>
          <!-- CAD图层 -->
          <div class="tree">
            <el-tree
              :key="timeStamp"
              :data="cadLayerTree"
              ref="cadTreeRef"
              show-checkbox
              auto-expand-parent
              node-key="id"
              :default-expanded-keys="[-1]"
              @check-change="handleNodeCheckCAD"
            >
              <template #default="{ node, data }">
                <span
                  class="nodeLabel"
                  @mouseover="data.titleFullShow = data.iconShow && true"
                  @mouseleave="data.titleFullShow = data.iconShow && false"
                >
                  {{ node.label }}</span
                >
                <img
                  src="@/assets/images/icon/标签页/详细信息.png"
                  @click="getDetail(data)"
                  class="nodeIcon"
                  v-show="data.iconShow"
                />
                <transition name="fade1">
                  <div class="fullTitle" v-show="true">
                    {{ node.label }}
                  </div>
                </transition>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template> 

<script>
/* eslint-disable */
import { getCurrentInstance, onMounted, ref } from "vue";
import pubsub from "pubsub-js";
import { useRouter } from "vue-router";
import axios from "axios";

import urlList from "@/store/urlList.json";
import message from "@/components/Message/showMessage";

export default {
  name: "mapControl",
  data() {
    return {
      timeStamp: new Date().getTime(),
      subList: [],
      treeShow: true,
      collapseShow: false,
      defaultCheckedList: [],
      tabs: [
        {
          text: "图层管理",
          selected: false,
          img: "图层管理-未选",
          node: "collaspe",
        },
        {
          text: "图层选择",
          selected: true,
          img: "图层选择",
          node: "tree",
        },
      ],
      legendList: [],
      tree: [],
      diyTree: [
        {
          id: -1,
          label: "自定义标注图层",
          children: [
            {
              id: "-1",
              label: "点标注",
              children: [],
              iconShow: false,
            },
            {
              id: "-1",
              label: "面标注",
              children: [],
              iconShow: false,
            },
          ],
        },
      ],
      cadLayerTree: [
        {
          id: -1,
          label: "CAD图层",
          class: "",
          iconShow: false,
          children: [
            {
              id: "-1",
              label:
                "南沙区高压变电站站址（更新万龙、湿地公园、横沥、庆盛03站位置）",
              children: [],
              iconShow: true,
              titleFullShow: false,
            },
            {
              id: "-1",
              label: "面标注",
              children: [],
              iconShow: true,
              titleFullShow: false,
            },
          ],
        },
      ],
      emptyShow: true,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const SampleData = require("../../store/mainTree.json");
    const commonTreeRef = ref(null);
    const diyTreeRef = ref(null);
    const cadTreeRef = ref(null);
    const layerName = ref("");
    let collapseRef = ["1"];
    const router = useRouter();

    onMounted(() => {
      // 订阅
      subscribeList();
      // 开启现状的图层
      openDefaultMap();
      // 基础地图树型对象补id
      addMapId();
    });

    // 基础地图树型对象补id
    function addMapId() {
      let index = 0;
      SampleData.forEach((data) => {
        data.children.forEach((e) => {
          e.id = index.toString();
          index++;
        });
      });
      // console.log(SampleData);
      proxy.tree = SampleData;
    }

    // 订阅
    function subscribeList() {
      proxy.subList.push(
        // 图层列表更新
        pubsub.subscribe("mapControllRenew", (n, data) => {
          let index = 1;
          data.forEach((element) => {
            switch (element.type) {
              case "point":
                proxy.diyTree[0].children[0].children.push({
                  id: index,
                  label: element.name,
                  iconShow: "true",
                  type: element.type,
                  featureId: element.id,
                  centerPoint: element.centerPoint,
                });
                break;
              case "polyline":
                break;
              case "polygon":
                // console.log(proxy.diyTree[0].children);
                proxy.diyTree[0].children[1].children.push({
                  id: index,
                  label: element.name,
                  iconShow: "true",
                  type: element.type,
                  featureId: element.id,
                  centerPoint: element.centerPoint,
                });
                break;
            }
            index++;
          });
          // console.log(proxy.diyTree);
          proxy.timeStamp = new Date().getTime();
          setTimeout(() => {
            for (let i = index; i > 0; i--) {
              diyTreeRef.value.setChecked(i.toString(), true, true);
            }
          }, 300);
        })
      );
    }

    // 开启现状的图层
    function openDefaultMap() {
      axios({
        method: "get",
        url: urlList.serverURL + "readMap",
      }).then((res) => {
        let list = res.data.result;
        proxy.tree.forEach((data) => {
          data.children.forEach((d) => {
            list.forEach((element) => {
              if (element.name === d.label) {
                commonTreeRef.value.setChecked(d.id, true, true);
              }
            });
          });
        });
      });
    }

    //处理树形列表地图要素开关事件(基础地图)
    function handleNodeCheckMain(nodeData, isChecked, haveChild) {
      // 父节点免处理
      if (nodeData.id != -1) {
        // 发布
        pubsub.publish("basicalMapChange", { nodeData, isChecked });
        // 提交服务器
        axios({
          method: "get",
          url: urlList.serverURL + "updateMap",
          params: { label: nodeData.label, isChecked },
        });
        // 开启地图要素显示
        if (isChecked) {
          // 读取图例
          axios({
            method: "get",
            url: urlList.mapURL + nodeData.label + "/MapServer/legend",
          }).then((res) => {
            let picSrc = res.data.split('src="')[1].split('" alt')[0];
            proxy.legendList.push({
              picSrc,
              label: nodeData.label,
              opacity: 20,
            });
          });
        }
        // 关闭地图要素显示
        else {
          proxy.legendList.forEach((element) => {
            if (element.label === nodeData.label) {
              proxy.legendList.splice(proxy.legendList.indexOf(element), 1);
            }
          });
        }
      }
    }

    //处理树形列表地图要素开关事件(自定义标注地图)
    function handleNodeCheckDIY(nodeData, isChecked, haveChild) {
      // 父节点免处理
      if (nodeData.id != -1) {
        console.log(nodeData);
        // 开启地图要素显示
        if (isChecked) {
          // 发布
          pubsub.publish("drawingChange", { nodeData, isChecked });
        }
        // 关闭地图要素显示
        else {
          pubsub.publish("drawingChange", { nodeData, isChecked });
        }
      }
    }

    // 处理树形列表地图要素开关事件(自定义标注地图)
    function handleNodeCheckCAD(nodeData, isChecked, haveChild) {}

    // 标签页切换
    function tabChange(event) {
      let node;
      if (event.target.nodeName === "IMG") {
        node = Array.from(event.target.parentNode.children)[1];
      } else if (event.target.nodeName === "SPAN") {
        node = event.target;
      } else {
        return;
      }
      let tabName = node.innerHTML;
      proxy.tabs.forEach((element) => {
        if (element.text === tabName) {
          if (element.selected) {
            return;
          } else {
            proxy.treeShow = !proxy.treeShow;
            proxy.collapseShow = !proxy.collapseShow;
            bigLegendHover();
            element.selected = true;
            element.img = element.text;
          }
        } else {
          element.selected = false;
          element.img = element.text + "-未选";
        }
      });
    }

    // 大图例hover效果
    function bigLegendHover() {
      let nodeList = Array.from(document.querySelectorAll(".bigLegend>div"));
      nodeList.forEach((node) => {
        let img = Array.from(node.children)[1];
        img.addEventListener("mouseover", () => {
          let legendName = Array.from(Array.from(node.children)[0].children)[0]
            .innerHTML;
          pubsub.publish("legendHover", {
            show: true,
            text: legendName,
          });
        });
        img.addEventListener("mouseout", () => {
          pubsub.publish("legendHover", {
            show: false,
          });
        });
      });
    }

    // 图层z坐标控制
    function layerIndexChange(event) {
      // 读取图层名
      let name = event.target.parentNode.firstChild.wholeText
        .split("| ")[1]
        .split(" ")[0];
      // 停止事件冒泡
      event.stopPropagation();
      // 次序交换
      for (let i = 0; i < proxy.legendList.length; i++) {
        if (proxy.legendList[i].text === name) {
          // 图层上移
          if (event.target.className === "titleIcon1") {
            if (i != 0) {
              let temp = proxy.legendList[i - 1];
              proxy.legendList[i - 1] = proxy.legendList[i];
              proxy.legendList[i] = temp;
              // 传输给地图
              pubsub.publish("layerIndexChange", {
                isUp: true,
                changedIndex: i,
              });
            }
          }
          // 图层下移
          else {
            if (i != proxy.legendList.length - 1) {
              let temp = proxy.legendList[i + 1];
              proxy.legendList[i + 1] = proxy.legendList[i];
              proxy.legendList[i] = temp;
              // 传输给地图
              pubsub.publish("layerIndexChange", {
                isUp: false,
                changedIndex: i,
              });
            }
          }
        }
      }
      // console.log(proxy.legendList);
    }

    //  查询具体标注
    function getDetail(data) {
      // console.log(data);
      // 读取要素ID
      let id = data.featureId;
      // 路由跳转
      router.push({
        path: "/mapLayout/detail",
        query: { id },
      });
      // 视图变更
      pubsub.publish("setView", [
        data.centerPoint[0],
        data.centerPoint[1] + 120,
      ]);
      // 信息更新
      pubsub.publish("drawingDetailData", { id });
    }

    // 图层透明度调整
    function sliderChange(data) {
      pubsub.publish("opacityChange", {
        label: data.label,
        opacity: data.opacity,
      });
    }

    // 图层名称查询
    function layerSearch() {
      // 读取输入值
      let name = layerName.value;
      proxy.tree.concat(proxy.diyTree).forEach((element) => {
        element.children.forEach((layer) => {
          if (layer.label.indexOf(name) != -1) {
            console.log(layer);
            // 开启图层显示
            commonTreeRef.value.setChecked(layer.id, true, true);
          }
        });
      });
    }

    // 查询回车确认
    function handleKeyPress(event) {
      if (event.keyCode === 13) {
        layerSearch();
      }
    }

    return {
      sliderChange,
      getDetail,
      SampleData,
      handleNodeCheckMain,
      handleNodeCheckDIY,
      handleNodeCheckCAD,
      commonTreeRef,
      diyTreeRef,
      cadTreeRef,
      layerName,
      tabChange,
      collapseRef,
      layerIndexChange,
      layerSearch,
      handleKeyPress,
    };
  },
  watch: {
    legendList: {
      handler(newValue) {
        this.emptyShow = !newValue.length > 0;
      },
      deep: true,
    },
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/variables.less";
.emptyLegend {
  text-align: center;
  > img {
    margin-top: 10%;
    width: 20%;
  }
}

.opactiySlider {
  display: inline-block;
  width: 150px;
  margin-left: 15px;
}

.nodeLabel {
  font-size: 17px !important;
  font-weight: 500;
  color: #303133 !important;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出隐藏 */
  text-overflow: ellipsis; /* 使用省略号表示截断的文本 */
}

.nodeIcon {
  width: 15px;
  margin-left: 2%;
}

.fullTitle {
  position: absolute;
  z-index: 99999999;
  background-color: #fafafa;
  left: 0%;
  border: red 1px solid;
  width: 100%;
}

.titleIcon1 {
  position: absolute;
  right: 14%;
  width: 20px;
}
.titleIcon2 {
  position: absolute;
  right: 8%;
  width: 20px;
}
.collaspe {
  width: 100%;
  position: absolute;
}
.layerSearcher {
  padding: 1.5%;
}
.tree {
  width: 96%;
  // position: absolute;
  margin: 0% 2%;
}

.treeContainer {
  position: absolute;
  top: 5.5%;
  // right: 0.25%;
  left: 0.25%;
  // float: right;
  height: 94%;
  width: 15%;
  background-color: white;
  z-index: 99999;
  border-radius: 5px;
  overflow: auto !important;
}
.panel-title {
  background-color: white;
  font-size: 120%;
  text-align: left;
  position: relative;
  > .bgBar {
    border-bottom: #e6e6e6 3px solid;
    float: left;
    position: absolute;
    top: 95%;
    width: 100%;
    background-color: #303133;
  }
  > .tab {
    position: relative;
    z-index: 9999;
    > .selected {
      display: inline-block;
      color: @mainColor;
      padding: 2%;
      border-bottom: @mainColor 3px solid;
      > img {
        width: 20px;
        margin-right: 1px;
      }
      > span {
        vertical-align: middle;
      }
    }
    > .unselected {
      display: inline-block;
      padding: 2%;
      color: #303133;
      > img {
        width: 20px;
        margin-right: 1px;
      }
      > span {
        vertical-align: middle;
      }
    }
  }
}
.smallLegend {
  margin: 0 15px;
  display: inline-block;
  height: 30px;
  > div {
    position: relative;
    left: 5.5%;
    // top: 10px;
    height: 30px;
    > span {
      font-size: 110%;
    }
    > .small {
      min-height: 30px;
      min-width: 30px;
    }
  }
}
.bigLegend {
  > div {
    position: relative;
    left: 5.5%;
    > span {
      font-size: 120%;
    }
    > .big {
      display: block;
      width: 90%;
    }
  }
}
.fade1-enter-active {
  transition: all 0.3s;
}
.fade1-leave-active {
  transition: all 0.3s;
  transform: translateX(-100%);
}
.fade1-enter-from,
.fade1-leave-to {
  transition: 0.3s;
  transform: translateX(-100%);
}
.fade2-enter-active {
  transition: all 0.3s;
}
.fade2-leave-active {
  transition: all 0.3s;
  transform: translateX(-100%);
}
.fade2-enter-from,
.fade2-leave-to {
  transition: 0.3s;
  transform: translateX(-100%);
}
.el-tree {
  background: rgba(6, 19, 31, 0) !important;
}
.treeContainer::-webkit-scrollbar {
  width: 0px;
}
</style>